package com.xctech.yace.swing.tab;

import com.xctech.yace.main.YaceSendFromDB;
import com.xctech.yace.swing.ConfigValue;
import com.xctech.yace.swing.FatherSwing;
import com.xctech.yace.swing.InitFileConfig;
import com.xctech.yace.swing.subTab.MonitorSwing;
import com.xctech.yace.util.StringUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;

import static javax.swing.JOptionPane.*;

public class FromDBTabSwing extends FatherSwing implements ConfigValue, InitFileConfig {

    public static String title = "数据库";

    public static JSplitPane genFromDBSplitPanel() {
        //发送画板
        JPanel send = new JPanel();
        //监控画板
        JPanel monitor = new JPanel();

        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, send, monitor);
        splitPane.setDividerLocation(1100);

        MonitorSwing.placeComponentsRight(monitor);
        placeComponentsFromDBLeft(send);

        return splitPane;
    }

    private static void placeComponentsFromDBLeft(JComponent panel) {
        /* 布局部分我们这边不多做介绍
         * 这边设置布局为 null
         */
        panel.setLayout(null);

        Properties properties = productPropties();
        Properties dbproperties = dbPropties();
        String ipport = properties.getProperty("bootstrap.servers");
        String dbipport = dbproperties.getProperty("url");

        /*
         * topic
         */
        JComboBox topicBox=new JComboBox();    //创建JComboBox
        topicBox.addItem("--自定义主题--");    //向下拉列表中添加一项
        topicMap.entrySet().stream().forEach(topics->{
            topics.getValue().stream().forEach(topic->{
                topicBox.addItem(topic);
            });
        });
        topicBox.setBounds(15,20,sfiledW+50,height);
        topicBox.setToolTipText(ipport);
        panel.add(topicBox);

        JTextField topicText = new JTextField(20);
        topicText.setBounds(15+sfiledW+space+40,20,200,height);
        topicText.setFont(new Font("Courier",Font.BOLD,13));
        topicText.setToolTipText(ipport);
        panel.add(topicText);

        /*
         * xid
         */
        JLabel xidLabel = new JLabel("事务号");
        xidLabel.setBounds(405,20,sfiledW,height);
        xidLabel.setFont(new Font("Courier",Font.BOLD,15));
        xidLabel.setToolTipText(dbipport);
        panel.add(xidLabel);

        JTextField xid = new JTextField(20);
        xid.setBounds(465,20,sfiledW+30,height);
        xid.setToolTipText(dbipport);
        panel.add(xid);

        // 发送按钮
        JButton startButton = new JButton("发送");
        startButton.setBounds(960,20,sfiledW,height);
        startButton.setToolTipText(ipport);
        panel.add(startButton);

        // 查询按钮
        JButton selectButton = new JButton("查询");
        selectButton.setBounds(840,20,sfiledW,height);
        selectButton.setToolTipText(dbipport);
        panel.add(selectButton);

        //sql查询
        JTextArea sql = new JTextArea(tip);
        sql.setBounds(20,20+height+space,1050,200);
        sql.setFont(new Font("Consolas",Font.BOLD,14));
        panel.add(sql);

        //message按钮
        JTextArea area = new JTextArea();
        JScrollPane scrollArea = new JScrollPane(area);

        scrollArea.setMaximumSize(scrollArea.getPreferredSize());
        scrollArea.setBounds(20,20+height+space+220,1050,650);
        area.setFont(new Font("Consolas",Font.BOLD,14));

//        scrollArea.setHorizontalScrollBarPolicy(
//                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrollArea.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        area.setEditable(false);//设置不可编辑
        panel.add(scrollArea);

        topicBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                topicText.setText("");//重置
                if(topicBox.getSelectedIndex()!=0){
                    String topic = topicBox.getSelectedItem().toString().trim();
                    topicText.setText(topic);
                }
            }
        });

        sql.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if(e.getKeyCode() == KeyEvent.VK_DELETE){
                    System.out.println("清空sql界面");
                    sql.setText("");
                }
            }
        });

        area.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if(e.getKeyCode() == KeyEvent.VK_DELETE){
                    System.out.println("清空查询结果界面");
                    area.setText("");
                }
            }
        });

        selectButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try{
                    String sqlStr = sql.getText().trim();
                    if("".equals(sqlStr)){
                        System.out.println("sql为空");
                        JOptionPane.showMessageDialog(null,"sql为空","sql select",WARNING_MESSAGE);
                        return;
                    }
                    //查询之前先清空
                    area.setText("");
                    List<Map<String,Object>> maps = YaceSendFromDB.selectMap(sqlStr);
                    JOptionPane.showMessageDialog(null,"查询完毕成功,一共"+maps.size()+"条数据","selectOK",INFORMATION_MESSAGE);

                    HashMap<String, Integer> lenMap = new HashMap<>();
                    for(int i = 0;i < maps.size(); i++){
                        Set<Map.Entry<String, Object>> entries = maps.get(i).entrySet();
                        entries.stream().forEach(m->{
                            Integer keylen = m.getKey().length();
                            Integer vallen = String.valueOf(m.getValue()).length();
                            String key = m.getKey();
                            Integer len = 0;
                            if(keylen >= vallen){
                                len = keylen;
                            }else {
                                len = vallen;
                            }
                            if(lenMap.containsKey(key)){
                                Integer tmp = lenMap.get(key);
                                if(len >= tmp){
                                    lenMap.remove(key);
                                    lenMap.put(key,len);
                                }
                            }else{
                                lenMap.put(key,len);
                            }
                        });
                    }
                    for(int i = 0;i < maps.size(); i++){
                        Set<Map.Entry<String, Object>> entries = maps.get(i).entrySet();
                        //输出表头
                        StringBuilder sb = new StringBuilder();
                        if(i == 0){
                            sb.append(StringUtil.lpad(String.valueOf(i),4));
                            entries.stream().forEach(k->{
                                sb.append("|");
                                sb.append(StringUtil.rpadSpace(k.getKey(),lenMap.get(k.getKey())));
                            });
                            sb.append("\n");
                        }

                        //输出表体
                        sb.append(StringUtil.lpad(String.valueOf(i+1),4));
                        entries.stream().forEach(m->{
                            sb.append("|");
                            String value = StringUtil.rpadSpace(String.valueOf(m.getValue()), lenMap.get(m.getKey()));
                            sb.append(value);
                        });
                        area.append(sb.toString()+"\n");
                    }
                }catch (Exception exception){
                    JOptionPane.showMessageDialog(null,"查询失败","selecterror",ERROR_MESSAGE);
                }
            }
        });

        startButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String xidStr = xid.getText().trim();
                String topicStr = topicText.getText().trim();
                if("".equals(topicStr)){
                    System.out.println("主题为空");
                    JOptionPane.showMessageDialog(null,"主题为空","kafkaSend",WARNING_MESSAGE);
                    return;
                }
                if("".equals(xidStr)){
                    System.out.println("xid为空");
                    JOptionPane.showMessageDialog(null,"事务号为空","kafkaSend",WARNING_MESSAGE);
                    return;
                }
                Boolean sendOk = YaceSendFromDB.syncSend(xidStr, topicStr);
                if(sendOk){
                    JOptionPane.showMessageDialog(null,"发送成功","kafkaSend",INFORMATION_MESSAGE);
                }else {
                    JOptionPane.showMessageDialog(null,"发送失败","kafkaSend",ERROR_MESSAGE);
                }

            }
        });

    }

}
